package org.pewpew.client;

import java.util.HashMap;
import java.util.Map;

import org.pewpew.model.Player;
import org.pewpew.model.WorldState;
import org.pewpew.server.GamePhysics;

import android.app.Activity;
import android.util.Log;
import android.widget.TextView;

final class ConsoleWorldObserver implements WorldObserver {
	private final Activity context;
	private Map<String, Boolean> playersNearby = new HashMap<String, Boolean> ();
	
	ConsoleWorldObserver(Activity mainActivity) {
		context = mainActivity;
	}

	public void update(GameModel gameModel, WorldState newWorld) {
		WorldState oldWorld =  gameModel.getWorldState();
		TextView consoleTextView = (TextView) context.findViewById(R.id.ConsoleTextView);
		StringBuilder console = new StringBuilder ();
		String myName = gameModel.getPlayerName();
		Player me = newWorld.getUsers().get(myName);
		for (Player anotherPlayer: newWorld.getUsers().values()) {
			String name = anotherPlayer.getUsername();
			Player anotherPlayerOldState = oldWorld.getUsers().get(name);
			if (anotherPlayerOldState == null) {
				anotherPlayerOldState = anotherPlayer;
			}
			
			checkDeadOrAlive(console, anotherPlayer, anotherPlayerOldState);
			checkDistance (console, me, anotherPlayer);
			checkIsLookingAtMe (console, me, anotherPlayer);
		}
	
		consoleTextView.append(console.toString());
	}

	private void checkIsLookingAtMe(StringBuilder console, Player me, Player anotherPlayer) {
	}

	private void checkDistance(StringBuilder console, Player me, Player anotherPlayer) {
		double distance = GamePhysics.distanceInMeters(anotherPlayer, me);
		Log.i ("PEW-observer", "Distance between " + me.getUsername() + " and " + anotherPlayer.getUsername() + " is " + Math.round(distance) + " m");
		String username = anotherPlayer.getUsername();
		boolean isNearby = distance < 10 * GamePhysics.WEAPON_DISTANCE;
		if (isNearby) {
			if (!playersNearby.containsKey(username)) {
				playersNearby.put(username, Boolean.TRUE);
				console.append(username + " is nearby [" +  Math.round (distance) + " m]\n");
			}
		}
		else {
			if (playersNearby.containsKey(username)) {
				playersNearby.remove(username);
				console.append(username + " leaves.\n");
			}
		}
	}

	private void checkDeadOrAlive(StringBuilder console, Player newPlayer, Player oldPlayer) {
		//check dead or alive status
		if (oldPlayer.getDead() != newPlayer.getDead()) {
			if (newPlayer.getDead()) {
				console.append(newPlayer.getUsername() + " dies!!!\n");
			}
			else {
				console.append(newPlayer.getUsername() + " is alive again.\n");
			}
		}
	}
}